<template>
  <div class="app-container">
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form label-position="left" label-width="100px" :model="readerForm" :rules="rules" ref="readerForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据库源：" prop="sourceId" label-width="100px">
              <el-select v-model="readerForm.sourceId" filterable @change="rDsChange">
                <el-option v-for="item in rDsList" :key="item.id" :label="item.sourceName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="采集数据范围：" prop="sourceDatasourceScopeType" label-width="130px">
              <el-radio v-for="item in dictList('data_get_is_increment_new')" :key="'type' + item.label" v-model="readerForm.sourceDatasourceScopeType" :label="item.value" @change="handleRadioChange">
                {{ item.label }}
              </el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-if="readerForm.sourceDatasourceScopeType === '2'">
            <el-form-item label="时间段：" prop="showDatePicker" label-width="100px">
              <el-date-picker @change="handleDateRangeChange" v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="flex-wrap: nowrap" v-if="data.length > 0">
            <el-form-item label="选择表：" prop="selectedData" :span="24">
              <div class="edit_dev">
                <el-transfer
                  v-model="selectedData"
                  :data="data"
                  :titles="['待选', '已选']"
                  @change="handleChange"
                  :left-default-width="leftWidth"
                  :right-default-width="leftWidth"
                  filterable
                  @left-check-change="handleLeftCheckChange"
                >
                  <span slot-scope="{ option }">
                    {{ option.label }}
                    <span class="truncate" style="color: #8492a6; font-size: 13px; padding-left: 10px; padding-right: 15px">{{ option.tableComment }}</span>

                    <div class="selectColumn" style="width: 30%; float: right" v-if="readerForm.sourceDatasourceScopeType === '1' || readerForm.sourceDatasourceScopeType === '2'">
                      <el-select v-model="option.extractionTimeField" placeholder="选择时间字段" @change="handleSelectChange(option)">
                        <el-option v-for="item in option.columnList" :key="item.columnName" :label="item.columnInfo" :value="item.columnName" :disabled="item.disabled"> </el-option>
                      </el-select>
                    </div>
                  </span>
                  <!-- 自定义右侧选中栏的内容 -->
                  <template slot="right-footer">
                    <!-- <el-button @click="removeSelected">移除选中项</el-button> -->
                    <el-button @click="clearSelected">清空已选</el-button>
                  </template>
                </el-transfer>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="readerForm.jobName" />
        </el-form-item>

        <el-form-item label="任务目录" prop="directoryId">
          <el-select v-model="readerForm.directoryId" clearable placeholder="请选择" @clear="handleClear" ref="selectUpResId">
            <el-option hidden :value="readerForm.directoryId" :label="upResName"> </el-option>
            <el-tree :data="treeList" :props="treeProps" :expand-on-click-node="false" :check-on-click-node="true" @node-click="handleNodeClick"> </el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="readerForm.description" />
        </el-form-item>
        <!--          <el-form-item label="上传附件" prop="filePath">-->
        <!--            <el-input v-model="readerForm.filePath" />-->
        <!--          </el-form-item>-->
        <el-divider content-position="left">调度信息</el-divider>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <el-form-item label="调度类型" prop="scheduleType">
                <el-radio v-for="(item, index) in dictList('scheduling_type')" :key="index" v-model="readerForm.scheduleType" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <el-form-item label="调度时间" prop="scheduleTime" v-if="readerForm.scheduleType == '0'">
                <el-date-picker v-model="readerForm.scheduleTime" type="datetime" placeholder="选择日期时间"> </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24" v-if="readerForm.scheduleType == '1'">
            <el-form-item label="生效日期：" prop="sourceDatasourceScopeType">
              <el-date-picker @change="handleDateRangeChange" v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="readerForm.scheduleType == '1'">
            <el-form-item label="调度时间：" prop="cronExpression">
              <el-input v-model="readerForm.cronExpression" @focus="dialogCron = true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark" v-if="readerForm.scheduleType != '2'">
              <el-form-item label="重跑次数" prop="rerunTime">
                <el-input v-model="readerForm.rerunTime" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark" v-if="readerForm.scheduleType != '2'">
              <el-form-item label="提前调度" prop="advanceScheduling">
                <el-radio v-for="(item, index) in dictList('advance_scheduling')" :key="index" v-model="readerForm.advanceScheduling" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <el-form-item label="调度等级" prop="scheduleLevel">
                <el-radio v-for="(item, index) in dictList('scheduling_level')" :key="index" v-model="readerForm.scheduleLevel" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-dialog title="设置执行策略" :visible.sync="dialogCron" :append-to-body="true" :close-on-click-modal="false">
        <Crontab @fill="getStr" @hide="dialogCron = false"></Crontab>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="init()">取 消</el-button>
        <el-button type="primary" @click="createJob">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as jobTemplate from '@/api/dataextractionrealtime/single.js'
import Bus from '../busReader'
import { listDataSource } from '@/api/metadata/sqlconsole'
import { getTableList } from '@/api/masterdata/masterdataTable'
import { fetchcolumnList } from '@/api/metadata/column'
import SqlEditor from '@/components/SqlEditor'
import StyleSelect from '@/views/customToolbar/component/styleSelect'
import Crontab from '@/components/Crontab/index.vue'
import { fetchMasterdataDirectoryList } from '@/api/masterdata/masterdataDirectory'

import { addDataextractionJob } from '@/api/dataextractionrealtime/single.js'
export default {
  name: 'TableMapper',
  components: { StyleSelect, SqlEditor, Crontab },
  data() {
    return {
      dialogVisible: true,
      dialogTableVisible: false,
      searchText: '', // 搜索关键词
      showCondition: false,
      tableHeight: '300px',
      dialogFormVisible: true,
      rDsList: [],
      rTbList: [],
      schemaList: [],
      columns: [],
      rColumnList: [], //列名数组
      loading: false,
      active: 1,
      customFields: '',
      customType: '',
      customValue: '',
      dataSource: '',

      rules: {
        sourceId: [{ required: true, message: '数据库源为必填项', trigger: 'change' }],
        sourceDatasourceScopeType: [{ required: true, message: '采集数据范围为必填项', trigger: 'change' }],
        // selectedData: [{ required: true, message: '数据库表为必填项', trigger: 'change' }],
      },
      tableData: [],
      waitList: [],
      selColumnList: [],
      nowSql: '',
      selColumnListFilter: [],
      dateRange: [],
      showDatePicker: false,
      selectedData: [],
      data: [],
      leftWidth: '300px', // 左侧面板宽度
      rightWidth: '300px', // 右侧面板宽度
      selectedItem: null,
      selectedOption: null,
      firstClick: false,
      monmentInfo: [],
      mapperJson: {},
      dialogCron: false,
      temp: {},
      fromTablesList: [],
      toTablesList: [],
      dateRange: [],
      readerForm: {
        sourceId: undefined,
        sourceName: undefined,
        columns: [],
        tableName: '',
        tableId: [],
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        querySql: '', //sql语句
        sourceDatasourceScopeType: '',
        where: '', //where语句
        startTime: '',
        endTime: '',

        extractionTimeField: '',
        jobName: '', //任务名称
        jobGroup: '', //任务目录
        description: '', //任务描述
        lcheckAll: false,
        rcheckAll: false,
        isIndeterminate: true,
        extractionName: '',
        status: '1',

        filePath: '', //附件地址
        scheduleType: '', //调度类型
        scheduleLevel: '', //调度级别
        advanceScheduling: '0', //提前调度

        rerunTime: '', //重跑次数
        scheduleTime: '', //调度时间
        cronExpression: '', //corn表达式
        effectTime: '', //开始时间
        failureTime: '', //结束时间
        directoryId: '',
      },
      rules: {
        jobName: [{ required: true, message: '任务名称为必填项', trigger: 'change' }],
        directoryId: [{ required: true, message: '任务目录为必填项', trigger: 'change' }],
        scheduleTime: [{ required: true, message: '调度时间为必填项', trigger: 'change' }],
        cronExpression: [{ required: true, message: '调度时间为必填项', trigger: 'change' }],
        scheduleType: [{ required: true, message: '调度类型为必填项', trigger: 'change' }],
        scheduleLevel: [{ required: true, message: '调度等级为必填项', trigger: 'change' }],
      },
      selectedOption: 'custom', // 默认选中自定义
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '10',
      },
      treeProps: {
        children: 'children',
        label: 'label',
      },
      treeList: [],
      selectedNode: null, // 选中的节点
      treeVisible: false, // 控制树是否可见
      listQuery: {
        jobName: undefined,
        dbType: undefined,
        executeStatus: undefined,
        checkStatus: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      upResName: '',
    }
  },
  computed: {
    // 使用计算属性过滤数据
    filteredData() {
      return this.tableData.filter((item) => {
        // 使用关键词搜索姓名字段
        return item.tableName.toLowerCase().includes(this.searchText.toLowerCase())
      })
    },
  },
  watch: {
    'readerForm.sourceId': function (oldVal, newVal) {
      // if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver' || this.dataSource === 'hana') {
      //   this.getSchema()
      // } else {
      //   this.getTables('reader')
      // }
    },

    selColumnList: function (oldVal, newVal) {},
  },
  mounted() {
    // const parentElementTwo = document.querySelector('.edit_dev').querySelector('.is-with-footer').querySelectorAll('.selectColumn');
    // parentElementTwo.forEach((item, index) => {
    //     item.style.display = 'block';
    // });
    if (!this.readerForm.sourceDatasourceScopeType) {
      // this.readerForm.sourceDatasourceScopeType = '1';
    } else {
      if (this.readerForm.sourceDatasourceScopeType === '2') {
        setTimeout(function () {
          const parentElementTwo = document.querySelector('.edit_dev').querySelector('.is-with-footer').querySelectorAll('.selectColumn')
          parentElementTwo.forEach((item, index) => {
            item.style.display = 'block'
          })
        }, 3000) // 1000 毫秒等于 1 秒
      } else {
        setTimeout(function () {
          const parentElementTwo = document.querySelector('.edit_dev').querySelector('.is-with-footer').querySelectorAll('.selectColumn')
          parentElementTwo.forEach((item, index) => {
            item.style.display = 'block'
          })
        }, 3000) // 1000 毫秒等于 1 秒
      }
    }
  },
  created() {
    this.getTreeList()
    this.getJdbcDs()
  },
  watch: {
    readerForm: {
      deep: true,
      handler(newData) {
        this.$refs.readerForm.validate((valid) => {
          if (valid) {
            // 表单验证通过，执行提交操作
          } else {
            // 表单验证失败，显示错误信息
            console.log('表单验证失败')
          }
        })
        // 当表单数据发生变化时触发自定义事件
        console.log('值改变' + JSON.stringify(newData))
      },
    },
  },
  methods: {
    // 创建单任务
    createJob() {
      this.readerForm.tableId = this.selColumnList
      console.log(this.selColumnList)
      const jbconfig = {
        filePath: this.readerForm.filePath,
        scheduleType: this.readerForm.scheduleType,
        scheduleLevel: this.readerForm.scheduleLevel,
        advanceScheduling: this.readerForm.advanceScheduling,
        scheduleTime: this.chaneDate(this.readerForm.scheduleTime),
        rerunTime: this.readerForm.rerunTime,
        cronExpression: this.readerForm.cronExpression,
        effectTime: this.chaneDate(this.readerForm.effectTime),
        failureTime: this.chaneDate(this.readerForm.failureTime),
      }
      console.log(this.readerForm)
      var arr = []
      for (var i = 0; i < this.readerForm.tableId.length; i++) {
        //读取信息配置
        var readerDto = {
          dateColumn: this.readerForm.tableId[i].onlyColumn,
        }
        // 映射数据
        var ColumnMappings = []
        for (var cl = 0; cl < this.readerForm.tableId[i].columnList.length; cl++) {
          let status
          if (this.readerForm.tableId[i].columnList[cl].status && this.readerForm.tableId[i].columnList[cl].status === true) {
            status = 1
          } else {
            status = 0
          }
          var mappingObj = {
            sourceColumn: this.readerForm.tableId[i].columnList[cl].columnName,
            targetColumn: this.readerForm.tableId[i].columnList[cl].sourceColumn,
            columnType: this.readerForm.tableId[i].columnList[cl].dataType,
            status: status,
          }
          ColumnMappings.push(mappingObj)
        }

        const dataExtractionDetailList = {
          targetTableName: this.readerForm.tableId[i].sourceTable,
          targetTableId: this.readerForm.tableId[i].sourceTableId,
          sourceTableName: this.readerForm.tableId[i].table,
          sourceTableId: this.readerForm.tableId[i].id,
          readerDto: readerDto,
          columnMappings: ColumnMappings,
        }
        console.log(dataExtractionDetailList)
        arr.push(dataExtractionDetailList)
      }
      // var readerDto ={
      //   dateColumn: this.read
      // }
      const obj = {
        extractionTimeField: this.readerForm.tableId[0].extractionTimeField,
        description: this.readerForm.description,
        jobName: this.readerForm.jobName,
        sourceDatasourceId: this.readerForm.sourceId,
        sourceDatasourceName: this.readerForm.sourceName,
        jobConfig: jbconfig,
        sourceDatasourceScopeType: this.readerForm.sourceDatasourceScopeType,
        jobGroup: '1692358527323836417',
        extractionStartTime: this.readerForm.startTime,
        extractionEndTime: this.readerForm.endTime,
        cronExpression: this.readerForm.cronExpression,
        directoryId: this.readerForm.directoryId,
        dataExtractionDetailList: arr,
        type: '2',
      }
      jobTemplate.addDataextractionJob(obj).then((res) => {
        if (res.data.code == 0) {
          this.init()
          this.active = 1
          this.rest()
          this.$message.success('添加成功')
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
          this.$message.error('请检查您的配置信息是否正确')
        })
      // if(this.detailList.length==0){
      //   this.$message.error('请返回上一步检查所选数据')
      // }else{
      //       // 调api
      // jobTemplate.batchAddJob(obj).then(res => {
      //    
      //   // 切回第一步
      //   this.active = 1
      //   this.dialogFormVisible = false
      // })
      // }
    },
    init() {
      this.$emit('done')
    },
    handleDateRangeChange() {
      // 处理日期范围选择器的值变化事件
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        this.readerForm.startTime = this.dateRange[0]
        this.readerForm.endTime = this.dateRange[1]
      } else {
        this.readerForm.startTime = ''
        this.readerForm.endTime = ''
      }
    },
    handleLeftCheckChange(data, checked) {
      console.log('左侧复选框状态变化')
      console.log('选中的数据：', data)
      console.log('是否选中：', checked)
      fetchcolumnList({ sourceId: checked[0] }).then((res) => {
        if (res.data.code === 0) {
          var dataInfo = res.data.data
          var columnList = []
          for (let i = 0; i < dataInfo.length; i++) {
            var cobj = {
              columnName: dataInfo[i].columnName,
              columnComment: dataInfo[i].columnComment,
              columnInfo: dataInfo[i].columnName + dataInfo[i].columnComment,
            }
            columnList.push(cobj)
          }
          this.monmentInfo = this.data.filter((item) => checked.includes(item.key))
          const index = this.data.findIndex((item) => item.id === checked[0])
          // console.log("====变更前"+JSON.stringify(this.data[index]))
          this.data[index].columnList = columnList
          // console.log("====变更后"+JSON.stringify(this.data[index]))
          // console.log("====monmentInfo"+JSON.stringify(this.monmentInfo))
          // console.log("===="+index)
          // .columnList = columnList;
        } else {
          console.log('未获取到')
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
          this.$emit('done')
        })
        .catch((_) => {})
    },
    handleSelectChange(row) {
      console.log('====变更前111' + JSON.stringify(this.selColumnList))
      console.log('====变更前111' + JSON.stringify(this.selColumnList))
      // 处理 el-select 的选项变化事件
      // this.monmentInfo=this.data.filter(item => row.key.includes(item.key));
      const index = this.selColumnList.findIndex((item) => item.id === row.id)
      console.log('====变更前1' + JSON.stringify(this.data[index]))
      console.log('====变更前2' + JSON.stringify(this.selColumnList[index]))
      this.selColumnList[index].extractionTimeField = row.extractionTimeField
      console.log('====变更后3' + JSON.stringify(this.data[index]))
      console.log('选中的选项:', row)
      console.log('选中的选项-当前selColumnList=:' + JSON.stringify(this.selColumnList))
      // 在这里可以执行其他操作
    },
    handleChange(value) {
      if (value.length > 1) {
        this.$message.warning('只能选择一项进行操作！')
        this.selectedData.pop()
      } else {
        // console.log("穿梭框选中的内容==="+JSON.stringify(this.data.filter(item => value.includes(item.key))))
        this.selColumnList = this.data.filter((item) => value.includes(item.key))
        setTimeout(function () {
          const parentElementTwo = document.querySelector('.edit_dev').querySelector('.is-with-footer').querySelectorAll('.selectColumn')
          parentElementTwo.forEach((item, index) => {
            item.style.display = 'block'
          })
        }, 1000) // 1000 毫秒等于 1 秒
      }
    },
    removeSelected() {
      // 移除选中项的逻辑
      this.selectedData = []
    },
    clearSelected() {
      // 清空选中项的逻辑
      this.selectedData = []
    },
    changeTextarea(val) {
      this.temp.executeStatement = val
    },
    handleBeforeClose(done) {
      this.dialogFormVisible = false
      // this.readerForm.tableId = this.waitList;
      this.readerForm.tableId = this.selColumnList
      this.rest()

      this.$emit('change', this.readerForm)
    },

    handleRadioChange(value) {
      // 处理选项变化事件
      console.log('选项发生变化，新值为：', value)
      if (value === '0') {
        this.readerForm.sourceDatasourceScopeType = '0'
      } else if (value === '1') {
        this.readerForm.sourceDatasourceScopeType = '1'

        const parentElementTwo = document.querySelector('.edit_dev').querySelector('.is-with-footer').querySelectorAll('.selectColumn')
        parentElementTwo.forEach((item, index) => {
          item.style.display = 'block'
        })
      } else {
        this.readerForm.sourceDatasourceScopeType = '2'
        const parentElementTwo = document.querySelector('.edit_dev').querySelector('.is-with-footer').querySelectorAll('.selectColumn')
        parentElementTwo.forEach((item, index) => {
          item.style.display = 'block'
        })
      }
    },
    handleSelectionChange(val) {
      // console.log("选中的行="+JSON.stringify(val))
      var arr = []
      val.forEach(function (element) {
        element.columnList = []
        let columnListAll = []
        fetchcolumnList({ sourceId: element.id }).then((res) => {
          // console.log("获取表列==="+JSON.stringify(res))
          if (res.data.code === 0) {
            columnListAll = res.data.data
            // console.log("当前获得表列数据1="+JSON.stringify(columnListAll))
            var columnInfo = []
            columnListAll.forEach(function (cloumn) {
              const cloObj = {
                columnName: cloumn.columnName,
                columnComment: cloumn.columnComment,
              }
              columnInfo.push(cloObj)
            })
            element.columnList = columnInfo
            console.log('当前获得表列数据2=' + JSON.stringify(element))
            arr.push(element)
            console.log('====选中的行数据666======' + JSON.stringify(arr))
          } else {
            console.log('未获取到')
          }
        })
        console.log('====选中的行数据888======' + JSON.stringify(arr))
      })

      this.selColumnList = arr
    },
    setselCol(arr) {
      this.selColumnList = arr
      console.log('====选中的行数据999======' + JSON.stringify(this.selColumnList))
    },

    chaneDate(datetime) {
      function addDateZero(num) {
        return num < 10 ? '0' + num : num
      }
      let d = new Date(datetime)
      let formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate())
      return formatdatetime
    },
    //获取列名
    rTbChange(id) {
      this.rTbList.forEach((item) => {
        if (item.id == id) {
          this.readerForm.tableName = item.tableName
        }
      })
      fetchcolumnList({ sourceId: id }).then((res) => {
        if (res.data.code === 0) {
          this.rColumnList = res.data.data
          console.log(this.rColumnList, 'list')
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    rest() {
      this.fromTablesList = []
      this.toTablesList = []

      this.rColumnList = []
      this.readerForm = {
        ltables: [],
        rtables: [],
        lcheckAll: false,
        rcheckAll: false,
        isIndeterminate: true,
        extractionName: '',
        status: '1',
        sourceId: undefined,
        sourceName: undefined,
        columns: [],
        tableName: '',
        tableId: '',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        querySql: '', //sql语句
        where: '',
      }
      this.rTbList = []
    },
    // 获取可用数据源
    getJdbcDs() {
      this.loading = true
      listDataSource().then((response) => {
        console.log(response, 'response')
        if (response.data.code == 200) {
          this.rDsList = response.data.data
          this.loading = false
          console.log(this.rDsList, 'rDsList')
        }
      })
    },
    // 获取表名
    getTables(type) {
      if (type === 'reader') {
        let obj = {}
        if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver' || this.dataSource === 'hana') {
          obj = {
            sourceId: this.readerForm.sourceId,
            tableSchema: this.readerForm.tableSchema,
          }
        } else {
          obj = {
            sourceId: this.readerForm.sourceId,
          }
        }
        // 组装
        getTableList({ sourceId: this.readerForm.sourceId }).then((res) => {
          if (res.data.code == 200) {
            this.rTbList = res.data.data
            this.tableData = []
            this.data = []
            for (let i = 0; i < this.rTbList.length; i++) {
              this.tableData.push({
                id: this.rTbList[i].id,
                tableName: this.rTbList[i].tableName + this.rTbList[i].tableComment,
                tableComment: this.rTbList[i].tableComment,
                table: this.rTbList[i].tableName,
              })
              this.data.push({
                key: this.rTbList[i].id,
                label: this.rTbList[i].tableName,
                tableName: this.rTbList[i].tableName + this.rTbList[i].tableComment,
                tableComment: this.rTbList[i].tableComment,
                table: this.rTbList[i].tableName,
                id: this.rTbList[i].id,
              })
              // console.log(JSON.stringify(this.tableData))
            }
          }
        })
      }
    },
    getSchema() {
      const obj = {
        sourceId: this.readerForm.sourceId,
      }
      // dsQueryApi.getTableSchema(obj).then(response => {
      //   this.schemaList = response
      // })
      getTableList(obj).then((res) => {
        if (res.data.code === 200) {
          this.schemaList = res.data.data
        }
      })
    },
    // schema 切换
    schemaChange(e) {
      this.readerForm.tableSchema = e
      // 获取可用表
      this.getTables('reader')
    },
    // reader 数据源切换
    rDsChange(e) {
      // 清空
      this.readerForm.tables = [] //选中表清空
      this.readerForm.tableName = ''
      this.readerForm.sourceId = e
      this.rDsList.find((item) => {
        if (item.id === e) {
          this.readerForm.sourceName = item.sourceName
          this.dataSource = item
        }
      })
      Bus.sourceId = e
      this.$emit('selectDataSource', this.dataSource)
      // 获取可用表
      this.getTables('reader')
    },
    rHandleCheckAllChange(val) {
      this.readerForm.columns = val ? this.rColumnList : []
      this.readerForm.isIndeterminate = false
    },
    rHandleCheckedChange(value) {
      console.log(value)
      const checkedCount = value.length
      this.readerForm.checkAll = checkedCount === this.rColumnList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.rColumnList.length
    },
    getData() {
      // if (Bus.sourceId) {
      //   this.readerForm.sourceId = Bus.sourceId
      // }
      return this.readerForm
    },
    //节点点击事件
    handleNodeClick(data) {
      // this.readerForm.jobGroup = node.label;
      // this.treeVisible = false; // 隐藏树
     

      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.upResName = data.name
      this.readerForm.directoryId =data.id

      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectUpResId.blur()
    },
    handleClear() {
      // 将选择器的值置空
      this.upResName = ''
      this.readerForm.directoryId = ''
    },
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.treeQuery).then((response) => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
            // this.$nextTick(() => {
            //     this.$refs.SlotTree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
            // });
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getStr(str) {
      this.temp.cronExpression = str
      this.readerForm.cronExpression = str
    },
    handleDateRangeChange() {
      // 处理日期范围选择器的值变化事件
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        this.readerForm.effectTime = this.dateRange[0]
        this.readerForm.failureTime = this.dateRange[1]
        console.log('开始日期:', this.startDate)
        console.log('结束日期:', this.endDate)
      } else {
        this.startDate = ''
        this.endDate = ''
      }
    },
    generateCronExpression() {
      if (this.selectedOption === 'custom') {
        // 根据用户输入生成自定义的 Cron 表达式
        this.cronExpression = `${this.second} ${this.minute} ${this.hour} ${this.dayOfMonth} ${this.month} ${this.dayOfWeek}`
      } else if (this.selectedOption === 'everyMinute') {
        this.cronExpression = '0 3 0 * * ?'
      } else if (this.selectedOption === 'everyHour') {
        this.cronExpression = '0 3 0 * * ?'
      } else if (this.selectedOption === 'everyDay') {
        this.cronExpression = '0 3 0 * * ?'
      }
      this.readerForm.cronExpression = this.cronExpression
    },
    handleRadioChange(value) {
      // 处理选项变化事件
      console.log('选项发生变化，新值为：', value)
    },

    lHandleCheckAllChange(val) {
      this.readerForm.ltables = val ? this.fromTablesList : []
      this.readerForm.isIndeterminate = false
    },
    rHandleCheckAllChange(val) {
      this.readerForm.rtables = val ? this.toTablesList : []
      this.readerForm.isIndeterminate = false
    },
    lHandleCheckedChange(value) {
      const checkedCount = value.length
      this.readerForm.lcheckAll = checkedCount === this.fromTablesList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.fromTablesList.length
    },
    rHandleCheckedChange(value) {
      const checkedCount = value.length
      this.readerForm.rcheckAll = value.length === this.toTablesList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.toTablesList.length
    },
    getLTables() {
      return this.readerForm.ltables
    },
    getRTables() {
      return this.readerForm.rtables
    },
    getConfigForm() {
      return this.readerForm
    },
    getName() {
      return this.readerForm
    },
  },
}
</script>

<style scoped>
.el-checkbox__label {
  width: 100%;
}
</style>
<style scoped>
.edit_dev {
  margin-left: 3%;
}

.edit_dev >>> .el-transfer-panel {
  width: 40%;
}

.edit_dev >>> .el-transfer-panel .el-transfer-panel__filter {
  width: 300px;
}

.edit_dev >>> .el-transfer-panel__body .selectColumn {
  display: none;
}

/*.edit_dev >>> .is-with-footer .selectColumn{*/
/*  display: none;*/
/*}*/
.edit_dev >>> . el-transfer-panel__item {
  width: 100%;
  flex-wrap: nowrap;
  display: flex;
}

.edit_dev >>> . el-transfer-panel__item .el-checkbox__label {
  width: 30%;
  float: right;
}

.center-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

span.truncate {
  display: inline-block;
  /* 将span元素设为块状元素以允许宽度设置 */
  max-width: 6em;
  /* 设置最大宽度为4个字符的宽度 */
  white-space: nowrap;
  /* 防止文字换行 */
  overflow: hidden;
  /* 隐藏超出容器宽度的内容 */
  text-overflow: ellipsis;
  /* 使用省略号表示被隐藏的文本 */
  vertical-align: bottom;
}

.el-checkbox {
  width: 100%;
}
</style>
